package cn.dapeng.rpc.server;


import cn.dapeng.rpc.common.codec.ServerByteToMessageDecoder;
import cn.dapeng.rpc.common.handler.ServerRequestHandlerV2;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ServerStartupV2 {
    public static void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup(5);

        ServerBootstrap sbs = new ServerBootstrap();
        sbs.group(boss, boss).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ServerByteToMessageDecoder())
                                .addLast(new ServerRequestHandlerV2());
                    }
                });

        int[] ports = {9000, 9001, 9002, 9003, 9004, 9005, 9006, 9007, 9008, 9009, 9010, 9011, 9012, 9013, 9014, 9015, 9016, 9017, 9018, 9019};
        for (int i = 0; i < ports.length; i++) {
            ChannelFuture bind = sbs.bind(ports[i]);
            System.out.println("server startup, port: %s listening ......".formatted(ports[i]));
            new Thread(() -> {
                try {
                    bind.sync().channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
}
